package com.kt.kvw.exception;

import com.kt.kvw.enums.ErrorCode;
import com.kt.kvw.model.respone.ResponseData;
import com.kt.kvw.util.ResponseDataUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * Created with IntelliJ IDEA.
 * Desc:
 *
 * @author: keen
 * Date: 2020-07-09
 * Time: 21:52
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseData<String> handlerBindException(ConstraintViolationException e) {
        StringBuilder sb = new StringBuilder();
        e.getConstraintViolations().stream().forEach(error -> sb.append(error.getMessage()).append(","));
        return ResponseDataUtils.fail(sb.toString());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseData<String> handlerBindException(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        e.getBindingResult().getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage()).append(","));
        return ResponseDataUtils.fail(sb.toString());
    }

    @ExceptionHandler(KwvApplicationException.class)
    public ResponseData<String> handlerBindException(KwvApplicationException e) {
        ErrorCode errorCode = e.getErrorCode();
        if (errorCode != null) {
            return ResponseDataUtils.fail(errorCode.getCode(), errorCode.getMessage());
        } else {
            return ResponseDataUtils.fail(e.getMessage());
        }
    }
}
